package com.jh.service.impl;

import com.jh.vo.InventoryDistributionVO;
import com.jh.vo.SalesTrendVO;
import com.jh.vo.TopSalesVO;
import com.jh.service.HomeService;
import com.jh.mapper.OrderMapper;
import com.jh.mapper.ProductMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HomeServiceImpl implements HomeService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public SalesTrendVO getSalesTrend(String startDate, String endDate) {
        LocalDate startLocalDate;
        LocalDate endLocalDate;

        // 处理日期参数
        try {
            if (startDate == null || endDate == null || startDate.isEmpty() || endDate.isEmpty()) {
                // 未提供日期或为空，仅返回前七天数据
                endLocalDate = LocalDate.now();
                startLocalDate = endLocalDate.minusDays(6);
            } else {
                startLocalDate = LocalDate.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE);
                endLocalDate = LocalDate.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE);

                // 验证日期范围合理性
                if (startLocalDate.isAfter(endLocalDate)) {
                    throw new IllegalArgumentException("开始日期不能晚于结束日期");
                }
                // 可选：限制最大日期范围（如1年）以优化性能
                if (ChronoUnit.DAYS.between(startLocalDate, endLocalDate) > 365) {
                    throw new IllegalArgumentException("日期范围不能超过1年");
                }
            }
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("日期格式无效，应为 YYYY-MM-DD", e);
        }

        // 转换为 LocalDateTime 用于数据库查询
        LocalDateTime startDateTime = startLocalDate.atStartOfDay();
        LocalDateTime endDateTime = endLocalDate.atTime(LocalTime.MAX);

        // 查询数据库
        List<Map<String, Object>> result = orderMapper.getSalesTrend(startDateTime, endDateTime);

        // 准备返回对象
        SalesTrendVO vo = new SalesTrendVO();
        List<String> dates = new ArrayList<>();
        List<BigDecimal> values = new ArrayList<>();

        // 生成日期范围
        LocalDate currentDate = startLocalDate;
        while (!currentDate.isAfter(endLocalDate)) {
            String dateStr = currentDate.format(DateTimeFormatter.ISO_LOCAL_DATE); // YYYY-MM-DD
            dates.add(dateStr);
            values.add(BigDecimal.ZERO); // 默认值为0
            currentDate = currentDate.plusDays(1);
        }

        // 填充数据库查询到的数据
        for (Map<String, Object> row : result) {
            String date = (String) row.get("date");
            BigDecimal value = (BigDecimal) row.get("value");
            int index = dates.indexOf(date);
            if (index != -1) {
                values.set(index, value != null ? value : BigDecimal.ZERO);
            }
        }

        vo.setDates(dates);
        vo.setValues(values);

        return vo;
    }
    @Override
    public List<InventoryDistributionVO> getInventoryDistribution() {
        return productMapper.getInventoryDistribution();
    }

    @Override
    public List<TopSalesVO> getTopSales() {
        return orderMapper.getTopSales();
    }
}